//用户的行为类型
var ActionType = {
	// 用户上线
	NEW_USER : 1,
	// 用户下线
	USER_LEAVE : 2,
	// 发送信息动作
	SEND_MSG : 3,
	
	INVALID_INPUT : 10000
};
// 消息对应的聊天类型
var ChatType = {
	// 私聊
	PRIVATE_CHAT : 1,
	// 群聊
	GROUP_CHAT : 2
};
// 消息类型
var MessageType = {
	// 普通的字符串消息
	NORMAL_TXT : 1,
	// 需要模板解析的字符串消息
	TEMPLATE_TXT : 2,
	// 系统回应消息：表示消息为当前用户的行为操作对应的系统回馈
	SYSTEM_ECHO : 3,
	// 系统的广播信息：表示消息为某个用户的行为触发给其他用户
	SYSTEM_BROADCAST : 4
};
// 消息发送者的类型
var SenderType = {
	// 普通用戶
	NORMAL_USER : 1,
	// 系统
	SYSTEM : 2
};

var HOST = (function() {
	var location = window.location;
	return {
		protocol : location.protocol,
		host : location.host,
		hostName : location.hostname,
		port : location.port
	};
})();
var defaults = {
	blockStyle:{
		color:'black',			//遮罩层默认颜色
		opacity:0				//遮罩层默认透明度（0：透明，1：不透明）
	},
	closeable:true,				//点击遮罩层是否可关闭弹出层，true:可关闭，false:不可关闭
	fadeTime:0,					//弹出层渐变时间
	marginTop:-1,				//弹出层距离顶部高度，默认居中
	single:false,				//是否只显示一个浮层；true：此浮层只会单独显示，显示时隐藏其他浮层
	scroll:false,				//浮层是否和页面一起滚动；true：浮层随页面一起滚动，false：浮层固定
	blockView:false				//是否显示遮罩层；true：显示（默认）
};

var log = {
	debug : function() {
		console.log('---', arguments);
	}
};

function messageBoxProperty(boxId, chatType, ws) {
	return {
		toId : boxId,
		chatType : chatType,
		ws : ws,
		msg : null,
		isCreateIfNotExist : true,
		isShow : true
	};
}

//聊天框对象集合
var CHAT_BOX_MAX = {};
//聊天框对象
var CHAT_BOX_CONTAINER = null;
//当前聊天框的chatBox对象
var CURRENT_CHAT_BOX = null;
//根据条件，进行聊天窗口对象的创建、展示消息和显示界面
function OPEN_MESSAGE_BOX_WITH_IF_EXISTS(param) {
	//boxId, chatType, ws, msg, isCreateIfNotExist
	if(param.isCreateIfNotExist == null || param.isCreateIfNotExist == 'undefined') {
		param.isCreateIfNotExist = true;
	}
	
	var chatBox = new ChatBox(param.toId, param.chatType, param.ws);
	
	//不存在指定聊天界面，而且不创建，则直接返回
	if(CHAT_BOX_MAX[chatBox.chatDivBoxId] == null && !param.isCreateIfNotExist) {
		return;
	}
	//创建聊天界面
	chatBox = chatBox.initBox();
	
	if(param.msg) {//追加聊天信息
		chatBox.showMessage(param.msg);
	}
	if(param.isShow) {//显示界面
		chatBox.show();
	}
}
function CLOSE_ALL_MESSAGE_BOX() {
	CHAT_BOX_CONTAINER.remove();
	CHAT_BOX_CONTAINER = null;
	CHAT_BOX_MAX = {};
}
//关闭聊天窗口
function CLOSE_MESSAGE_BOX_WITH_IF_EXISTS(chatBox) {
	if(chatBox) {
		//聊天内容显示框 
		chatBox.chatDivBoxObj.remove();
		//左侧导航栏
		chatBox.chatDivMinObj.remove();
		//聊天输入框
		chatBox.chatTextAreaObj.remove();
		chatBox.chatDivMinObj.remove();
		chatBox.chatDivBoxHtmlObj.remove();
		
		ChatBox.boxCount --;
		CHAT_BOX_MAX[chatBox.chatDivBoxId] = null;
		
		if(ChatBox.boxCount <= 0) {
			CHAT_BOX_CONTAINER.remove();
			CHAT_BOX_CONTAINER = null;
		} else {
			var last = null;
			for(var i in CHAT_BOX_MAX) {
				var temp = CHAT_BOX_MAX[i];
				if(temp != null) {
					last = temp;
				}
			}
			if(last) {
				last.show();
			}
		}
	}
}

//按钮触发的关闭聊天窗口
function closeCurrentChatBox() {
	CLOSE_MESSAGE_BOX_WITH_IF_EXISTS(CURRENT_CHAT_BOX);
}
function ChatBox(boxId, chatType, ws) {
	this.boxId = boxId;
	this.chatType = chatType;
	
	this.ws = ws;
	
	//聊天内容显示框 
	this.chatDivBoxObj = null;
	//左侧导航栏
	this.chatDivMinObj = null;
	//聊天输入框
	this.chatTextAreaObj = null;
	this.chatDivMinObj = null;
	this.chatDivBoxId = this.createChatBoxId('chat_box');
	this.chatDivMinId = this.createChatBoxId('min_bar');
	this.chatDivDragId = this.createChatBoxId('div_drag');
	this.chatDivTextAreaId = this.createChatBoxId('div_text_area');
	this.isExistAlready = false;
}
//统计当前有多少聊天框
ChatBox.boxCount = 0;
ChatBox.prototype.createChatBoxId = function(prev) {
	return prev + '___' + this.boxId + '__' + this.chatType;
};
//初始化聊天界面
ChatBox.prototype.initBox = function() {
	var temp = CHAT_BOX_MAX[this.chatDivBoxId];
	if(temp != null) {
		this.chatDivBoxObj = temp.chatDivBoxObj;
		this.chatDivMinObj = temp.chatDivMinObj;
		temp.isExistAlready = true;
		return temp;
	}
	//计数器
	ChatBox.boxCount ++;
	//不存在总聊天框，则创建 
	if(CHAT_BOX_CONTAINER == null || CHAT_BOX_CONTAINER.length < 1) {
		var html = '';
		var chatBoxContainerId = 'chatBoxContainer';
		
		var container = {w : 950, h : 560};
		var userList = {w : 217, h : container.h - 2};
		var divStatus = {w : container.w - userList.w - 2, h : 45};
		var input = {w : container.w - userList.w - 5, h : 100};
		var bottom = {w : container.w - userList.w - 4, h : 30};
		var boxDivs = {w : container.w - userList.w - 3, h : container.h - divStatus.h - input.h - bottom.h - 4};
		
		html += '<div id="' + chatBoxContainerId + '" style="width : ' + (container.w) + 'px; height : ' + container.h + 'px;">';
		html += '	<table border="0" id="chatBoxTable">';
		html += '		<tr>';
		html += '			<td style="border : 0px;" border="0">';
		html += '				<div id="chatBoxUserList" style="width : ' + (userList.w) + 'px; height : ' + userList.h + 'px;">';
		html += '					<div id="chatBoxUserListDiv" style="padding : 4px;" >';
							
		html += '					</div>';
		html += '				</div>';
		html += '			</td>';
		html += '			<td>';

		html += '				<div id="chatBoxDivStatus" style="width : ' + divStatus.w + 'px; height : ' + divStatus.h + 'px;">';
		html += '					<div id="chatBoxDivStatus_name" style="float : left;"></div>';
		html += '					<div style="float : right;">';
		html += '						<div id="chatBoxContainerClose" onclick="CLOSE_ALL_MESSAGE_BOX();">×</div>';
		html += '					</div>';
		html += '					<div style="clear : both;"></div>';
		html += '				</div>';

		html += '				<div id="chatBoxDivs" style="width : ' + boxDivs.w + 'px; height : ' + boxDivs.h + 'px;">';
		
		html += '				</div>';
		
		html += '				<div id="chatBoxTextAreaContainer" style="width : ' + input.w + 'px; height : ' + input.h + 'px;">';
		html += '					<textarea id="pmdTextarea_sample" class="pmdTextarea_sample"  style="display:none; width : ' + (input.w - 5) + 'px; height : ' + (input.h - 9) + 'px;" cols="90"></textarea>';
		html += '				</div>';

		html += '				<div id="chatBoxDivBottom" style="width : ' + bottom.w + 'px; height : ' + bottom.h + 'px; ">';
		html += '					<div style="padding-top : 4px; padding-right : 8px;">';
		html += '						<span class="chatInput" id="sendButton" >send</span>';
		html += '						<span class="chatInput" onclick="closeCurrentChatBox();" >close</span>';
		html += '					</div>';
		html += '				</div>';
		
		html += '			</td>';
		html += '		</tr>';
		html += '	</table>';
		html += '</div>';
		$('body').append(html);
		
		$('#sendButton').click(function() {
			//MessageType.NORMAL_TXT
			if(CURRENT_CHAT_BOX) {
				CURRENT_CHAT_BOX.sendMessageWithWebSocket(MessageType.NORMAL_TXT);
			}
		});
		
		var chatBoxContainer = CHAT_BOX_CONTAINER = $('#' + chatBoxContainerId);
		
		chatBoxContainer.easydrag();
		chatBoxContainer.setHandler('chatBoxUserList');
		chatBoxContainer.setHandler('chatBoxDivStatus');
		
		CHAT_BOX_CONTAINER.showPop(defaults);
		
		$('div.chatBoxUserItem').live('mouseover', function() {
			$(this).find('div.chatUserItemCloseDiv').fadeIn(0);
		});
		$('div.chatBoxUserItem').live('mouseout', function() {
			$(this).find('div.chatUserItemCloseDiv').fadeOut(0);
		});
		
		this.chatBoxDivStatusObj = $('#chatBoxDivStatus_name');
	} else {
		this.chatBoxDivStatusObj = $('#chatBoxDivStatus_name');
	}

	this.createBoxIfNotExist();
	return this;
};
//发送消息：通过使用持有的websocket对象，发送消息
ChatBox.prototype.sendMessageWithWebSocket = function(messageType) {
	var value = this.chatTextAreaObj.val();
	value = value.replace(/^\n+|\n+$/g,"");
	this.chatTextAreaObj.val('');
	if(value.length < 1) {
		this.showMessage({
			messageType : MessageType.NORMAL_TXT,
			actionType : ActionType.INVALID_INPUT
		});
	} else {
		//发送消息
		var msgObj = this.ws.sendMessage(this.boxId, this.chatType, messageType, value);
		//显示消息
		//this.showMessage(msgObj);
	}
};
//创建聊天内容框
ChatBox.prototype.createBoxIfNotExist = function() {
	if(this.chatDivBoxObj == null || this.chatDivBoxObj.length < 1) {
		var html = '';
		//$('#chatBoxDivs .privateMessageDiv').fadeOut(0);
		
		//聊天内容框 
		html += '<div id="' + this.chatDivBoxId + '" class="privateMessageDiv">';
		html += '	<div class="privateMessageHtml" style="padding : 5px;">';
		html += '	</div>';
		html += '</div>';
		$('#chatBoxDivs').append(html);

		this.chatDivBoxObj = jQuery('div#' + this.chatDivBoxId);
		CHAT_BOX_MAX[this.chatDivBoxId] = this;
		this.chatDivBoxHtmlObj = this.chatDivBoxObj.find('div.privateMessageHtml');
		
		//左侧导航框
		html = '';
		html += '<div id="' + this.chatDivMinId + '" class="chatBoxUserItem noSelected">';
		html += '	<div style="padding : 5px; " class="noSelected">';
		html += '' + this.chatDivMinId;
		html += '		<div class="chatUserItemCloseDiv" style="float:right; display : none;"><span class="chatUserItemClose">x</span></div>';
		html += '		<div style="clear : both;"></div>';
		html += '	</div>';
		html += '</div>';
		$('#chatBoxUserListDiv').append(html);
		
		//聊天输入框 	#chatBoxTextAreaContainer
		html = '';
		html += '<textarea id="' + this.chatDivTextAreaId + '" class="pmdTextarea" style="display:none;" ></textarea>';
		$('#chatBoxTextAreaContainer').append(html);
		this.chatTextAreaObj = $('#' + this.chatDivTextAreaId);
		//样例对应的样式 
		var sampleStyle = $('#pmdTextarea_sample');
		this.chatTextAreaObj.css({
			width : sampleStyle.width() + 'px',
			height : sampleStyle.height() + 'px'
		});
		var thisChatBox = this;
		//聊天输入框，回车事件：发送消息
		this.chatTextAreaObj.keyup(function(e) {
			var kc = e.keyCode;
			if(e.ctrlKey && e.keyCode == 13) {
				var value = jQuery(this).val();
				jQuery(this).val(value + '\n');
			} else if(kc == 13) {
				thisChatBox.sendMessageWithWebSocket(MessageType.NORMAL_TXT);
			}
			e.preventDefault();
		});
		
		
		var item = $('#' + this.chatDivMinId);
		this.chatDivMinObj = item;
		//chatBox
		var thisObj = this;
		//点击左侧导航显示聊天框
		item.click(function() {
			//$('#chatBoxDivs .privateMessageDiv').fadeOut(0);
			//thisObj.chatDivBoxObj.fadeIn(0);
			//setMessage(thisObj.thisObj, thisObj.chatType);
			thisObj.show();
			$(this).siblings().removeClass('chatBoxUserItemSelected');
			$(this).addClass('chatBoxUserItemSelected');
		});
		//关闭聊天按钮的触发
		//CLOSE_MESSAGE_BOX_WITH_IF_EXISTS
		item.find('span.chatUserItemClose').click(function() {
			CLOSE_MESSAGE_BOX_WITH_IF_EXISTS(thisObj);
		});
		
	}
};
//设置当前聊天信息
ChatBox.prototype.setMessageInfo = function(id, type) {
	CURRENT_TO_SESSION_ID = id;
	CURRENT_CHAT_TYPE = type;
};
//显示聊天框相关界面
ChatBox.prototype.show = function() {
	//this.chatDivBoxObj.showPop(defaults);
	this.chatDivBoxObj.siblings().fadeOut(0);
	this.chatDivBoxObj.fadeIn(0);

	//聊天文本输入框
	this.chatTextAreaObj.siblings().fadeOut(0);
	this.chatTextAreaObj.fadeIn(0);
	this.chatTextAreaObj.focus();
	
	//设置当前的聊天对象
	this.setMessageInfo(this.boxId, this.chatType);
	
	//聊天状态栏
	this.chatBoxDivStatusObj.html('<div style="padding : 10px; font-weight : bold;">' + this.chatDivBoxId + '</div>');

	this.chatDivMinObj.siblings().removeClass('chatBoxUserItemSelected');
	this.chatDivMinObj.addClass('chatBoxUserItemSelected');
	this.chatDivBoxHtmlObj.fadeIn(0);
	
	CURRENT_CHAT_BOX = this;
};

ChatBox.prototype.hide = function() {
	
	this.createBoxIfNotExist();
	
	this.chatDivBoxObj.hidePop();
};
//展示接收到的聊天内容
ChatBox.prototype.showMessage = function(msg) {
	if(ChatBox.boxCount <= 1) {
		this.show();
	}
	
	var html = '';
	var messageType = msg.messageType;
	if(messageType == MessageType.NORMAL_TXT) {//普通文本
		if(msg.actionType == ActionType.SEND_MSG) {	//普通的发送动作 
			var isSelf = CURRENT_SESSION_ID == msg.senderId;
			var userStyle = 'userStyle_other';
			if(isSelf) {
				userStyle = 'userStyle_self';
			}
			
			var width = this.chatDivBoxHtmlObj.width() - 40;
			html += '<div class="messageContainerDiv" style="width : ' + width + 'px;">';
			html += '	<div class="' + userStyle + '">';
			html += '		<span style="magin-right : 10px;">' + this.chatDivBoxId + '' + '</span>';
			html += '		<span>' + new Date().format('yyyy-MM-dd mm:hh:ss') + '</span>';
			html += '	</div>';
			html += '	<div class="messageContentStyle1">';
			html += '		<pre class="messageContentPre" style="width : ' + width + 'px;">' + messageContentTemplate(msg) + '</pre>';
			html += '	</div>';
			html += '</div>';	
		} else if(msg.actionType == ActionType.INVALID_INPUT) {	//输入非法
			html += '<div class="messageContainerDiv_system_info">';
			html += '	<span class="messageContainerDiv_system_info_span">发送消息不能为空</span>&nbsp;&nbsp;&nbsp;&nbsp;';
			html += '</div>';
		}
	} else if(messageType == MessageType.SYSTEM_BROADCAST) {	//系统的广播消息
		if(msg.actionType == ActionType.USER_LEAVE) {	//某个用户下线
			html += '<div class="messageContainerDiv_system_info">';
			html += '	<span class="messageContainerDiv_system_info_span">该用户已下线</span>&nbsp;&nbsp;&nbsp;&nbsp;';
			html += '</div>';
		} else if(msg.actionType == ActionType.NEW_USER) {	//某个用户下线
			html += '<div class="messageContainerDiv_system_info">';
			html += '	<span class="messageContainerDiv_system_info_span">该用户已上线</span>&nbsp;&nbsp;&nbsp;&nbsp;';
			html += '</div>';
		}
	}
	
	this.chatDivBoxHtmlObj.append(html);
	this.chatDivBoxObj.scrollTop(this.chatDivBoxHtmlObj[0].scrollHeight);
};

function messageContentTemplate(msg) {
	var messageValue = msg.messageContent;
	
	var http = "http://";
	var https = "https://";
	if(messageValue.length >= http.length && messageValue.substring(0, http.length) == http
			|| (messageValue.length >= https.length && messageValue.substring(0, https.length) == https)) {
		var html = '';
		html += '<span style="padding-top : 0px; margin-top : -12px;"><a style="color : blue;" href="' + messageValue + '" target="_blank">' + messageValue + '</a></span>';
		
		return html;
	}
	return messageValue;
}

function objToString(obj) {
	if (obj && typeof obj == 'object') {
		var s = '{';
		for ( var i in obj) {
			var value = obj[i];
			if (typeof value == 'object') {
				s += i + ': "' + objToString(value) + '",';
			} else {
				s += i + ':"' + value + '",';
			}
		}
		s += '}';
		return s;
	}
	return obj == null ? '{}' : obj;
}

Date.prototype.format = function(format){ 
	var o = { 
		"M+" : this.getMonth()+1, //month 
		"d+" : this.getDate(), //day 
		"h+" : this.getHours(), //hour 
		"m+" : this.getMinutes(), //minute 
		"s+" : this.getSeconds(), //second 
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
		"S" : this.getMilliseconds() //millisecond 
	};

	if(/(y+)/.test(format)) { 
		format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	} 

	for(var k in o) { 
		if(new RegExp("("+ k +")").test(format)) { 
			format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
		} ;
	} 
	return format; 
};